# _*_ coding:utf-8 _*_
"""
======================
author:mojin
@time:2023/3/21 13:42
@email:397135766@qq.com
======================
"""
import os
from common.logger import Logger


class BackupRecovery:
    def __init__(self, db_data,):
        self.host = db_data['host']
        self.user = db_data['user']
        self.password = db_data['password']
        self.database = db_data['database']
        self.port = db_data['port']

    def backup(self, db_path):
        """
        backup_cmd='mysqldump --column-statistics=0 -h192.168.1.234 -uroot -p123456 -P3306 mydb>mydb_bak.sql'
        mysqldump --column-statistics=0 -h 172.17.26.225 --default-character-set=utf8mb4 --opt --hex-blob --set-gtid-purged=OFF --user root -p it > it-2022-04-09_16_09_26.sql
        https://blog.csdn.net/hewusheng10/article/details/108093580
        因为新版的mysqldump默认启用了一个新标志，通过- -column-statistics=0来禁用他
        解决方法：mysqldump --column-statistics=0 -h ip -u root -p dbname > db.sql;
        :param db_path:
        :return:
        """
        backup_cmd=f'mysqldump --column-statistics=0 -h{self.host} -u{self.user} -p{self.password} -P{self.port} {self.database} > {db_path}'
        Logger.info(backup_cmd)
        code = os.system(backup_cmd)
        if code == 0:
            Logger.warning(f'备份[{db_path}]数据库执行成功！')
        else:
            Logger.error(f'备份[{db_path}]数据库执行失败！（{code}）')

    def recovery(self, db_path):
        backup_cmd=f'mysql -h{self.host} -u{self.user} -p{self.password} -P{self.port} {self.database} < {db_path}'
        Logger.info(backup_cmd)
        code = os.system(backup_cmd)
        if code == 0:
            Logger.warning(f'恢复[{db_path}]数据库执行成功！')
        else:
            Logger.error(f'恢复[{db_path}]数据库执行失败！（{code}）')

